﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.GateWay.CT_NBIoT.Utils;
using Atmk.WaterMeter.MIS.GateWay.CT_NBIoT.ViewModel;
using Atmk.WaterMeter.MIS.GateWay.CT_NBIoT.ViewModel.DevicesManage;
using Atmk.WaterMeter.MIS.GateWay.CT_NBIoT.ViewModel.NaRespon;
using Atmk.WaterMeter.MIS.GateWay.CT_NBIoT.ViewModel.RequestParam;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json;

namespace Atmk.WaterMeter.MIS.GateWay.CT_NBIoT.Visiters
{
    /// <summary>
    /// 电信NB平台的API接口访问管理类型。
    /// 包括注册、删除、查询、修改设备
    /// </summary>
    public class CT_NBIoT_DevicesVister : CT_NBIoT_BaseVister
    {
        /// <inheritdoc />
        public CT_NBIoT_DevicesVister(string appId, string appSecret, string platformIp, int port) : base(appId,
            appSecret, platformIp, port)
        {
            _MAppid = appId;
            _MAppsecret = appSecret;
            _HttpsUtil = new HttpsUtil(platformIp, port);
        }
        /// <summary>
        /// 注册设备
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="dmp"></param>
        /// <returns></returns>
        public ApiResult PostDevice(string accessToken, DeviceManagePostParameter dmp)
        {
            dmp.appId = _MAppid;
            var apiPath = $"{UrlManage.PostDevice}?appId={_MAppid}";
            var noGet = new List<string>
            {
                PropertyHelper.GetPropertyName<DeviceManagePostParameter>(d=>d.endUserId),
                PropertyHelper.GetPropertyName<DeviceManagePostParameter>(d=>d.psk),
                PropertyHelper.GetPropertyName<DeviceManagePostParameter>(d=>d.timeout)
            };
            var body = ReqParameterUtil.GetJsonParam(dmp, noGet.ToArray());
            var headers = new WebHeaderCollection
            {
                {"app_key", _MAppid},
                {"Authorization", "Bearer " + accessToken}
            };
            try
            {
                var apiresult = _HttpsUtil.PostUrl(apiPath, body, headers, "POST", "application/json");
                return apiresult;
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                _logger.Error(ex.StackTrace);
                return new ApiResult
                {
                    Errcode = ex.StackTrace,
                    Result = ex.Message,
                    StatusCode = -1
                };
            }
        }
        /// <summary>
        /// 修改设备
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="dmp"></param>
        /// <returns></returns>
        public ApiResult PutDevice(string accessToken, DeviceManagePutParameter dmp)
        {
            dmp.appId = _MAppid;
            var apiPath = $"{UrlManage.PutDevice}/{dmp.deviceId}?appId={_MAppid}";
            var noGet = new List<string>()
            {
                PropertyHelper.GetPropertyName<DeviceManagePutParameter>(d => d.mute),
                PropertyHelper.GetPropertyName<DeviceManagePutParameter>(d => d.isSecure)
            };
            noGet.AddRange(PropertyHelper.GetNoValuePropertyName(dmp));
            var body = ReqParameterUtil.GetJsonParam(dmp, noGet.ToArray());
            var headers = new WebHeaderCollection
            {
                {"app_key", _MAppid},
                {"Authorization", "Bearer " + accessToken}
            };
            try
            {
                var apiresult = _HttpsUtil.PostUrl(apiPath, body, headers, "PUT", "application/json");
                _logger.Info(apiresult.StatusCode + apiresult.Result);
                return apiresult;
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                _logger.Error(ex.StackTrace);
                return new ApiResult
                {
                    Errcode = ex.StackTrace,
                    Result = ex.Message,
                    StatusCode = -1
                };
            }
        }
        /// <summary>
        /// 删除设备
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public ApiResult DeleteDevice(string accessToken, string deviceId)
        {
            var apiPath = $"{UrlManage.DeleteDevice}/{deviceId}?&appId={_MAppid}";
            var headers = new WebHeaderCollection
            {
                {"app_key", _MAppid},
                {"Authorization", "Bearer " + accessToken}
            };
            try
            {
                var apiresult = _HttpsUtil.PostUrl(apiPath, string.Empty, headers, "DELETE", "application/json");
                _logger.Info(apiresult.StatusCode + apiresult.Result);
                return apiresult;
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                _logger.Error(ex.StackTrace);
                return new ApiResult
                {
                    Errcode = ex.StackTrace,
                    Result = ex.Message,
                    StatusCode = -1
                };
            }
        }

        /// <summary>
        /// 获取设备详细信息
        /// </summary>
        /// <param name="token"></param>
        /// <param name="dParam">设备请求参数类型</param>
        /// <returns></returns>
        public ApiResult GetDevice(string token, DeviceGetParam dParam)
        {
            dParam.appId = _MAppid;
            var urlParam = ReqParameterUtil.GetUrlParam(dParam,"pageNo","pageSize");
            var apiPath = $"{UrlManage.GetDevices}{urlParam}";
            var body = "";
            var method = "GET";
            var contenttype = "application/json";
            var headers = new WebHeaderCollection
            {
                { "app_key", _MAppid },
                { "Authorization", "Bearer " + token }
            };
            try
            {
                var apiresult = _HttpsUtil.PostUrl(apiPath, body, headers, method, contenttype);
                _logger.Info(apiresult.StatusCode + apiresult.Result);
                return apiresult;
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                _logger.Error(ex.StackTrace);
                return new ApiResult
                {
                    Errcode = ex.StackTrace,
                    Result = ex.Message,
                    StatusCode = -1
                };
            }
        }
    }
}